<?php

namespace App\Http\Middleware;

use Closure;
use App\Model\AdminUserModel;


class AdminNodeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 判断是否已经登录 末登录跳转到首页
        if (empty(session('Adminuser-data'))) {
            return redirect()->route('Admin.login')->with('message', '请先登录');
        }

        $user = session('Adminuser-data');

         // 收集放行权限列表
         $node = [];
         for ($i=2; $i < func_num_args(); $i++) {
             $node[] = func_get_arg($i);
         }

         // 判断你是否有权限
         // 获取用户的权限数组
         $node_role = [];
         foreach (AdminUserModel::find($user['id'])->roles as $role) {
             foreach ($role->nodes->toArray() as $value) {
                 $node_role[] = $value['name'];
             }
         }
         $node_role = array_unique($node_role);

         // 用数组的方式来求交集
         if (!array_intersect($node, $node_role)) {
             return redirect()->route('Admin.index')->with('message','你没有权限执行该操作');
         }
         //dd($user_roles);
         return $next($request);
    }
}
